package main.java.pers.seg.model.utils;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;

import static main.java.pers.seg.model.constants.ObjectConstants.viewcontainermap;
import static main.java.pers.seg.model.utils.NodeUtils.judgeElement;
import static main.java.pers.seg.model.utils.NodeUtils.judgeElement2;


public class HeadersUtils {
    public static void start(String filePath) throws Exception {
        if (filePath==null || filePath.isEmpty()){
            throw new Exception("filePath could not be null or empty!");
        }
        File file = new File(filePath);
        if(!file.exists() || !file.isFile() || !(file.getName().endsWith(".xml") || file.getName().endsWith(".core")))
            throw new Exception(filePath+" is not a xml file");
        if (!file.canRead()){
            throw new Exception("can not read "+filePath);
        }

        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(file);
            List<Element> headers = getHeaders(document);
            Iterator<Element> it = headers.iterator();
            while (it.hasNext()){
                Element e = it.next();
                Element headerFather = e.getParent(); //settingsActivity
                List<String> xpaths = new ArrayList<String>();
                getXpath(e,xpaths);
                List<Element> targets = getTargetElement(document,xpaths);
                Iterator<Element> tarIt = targets.iterator();
                while (tarIt.hasNext()){
                    Element tar = tarIt.next();
                    Element copy = (Element) tar.clone();
                    headerFather.add(copy);
                    judgeElement2(copy);

                }
            }

            FileOutputStream out = new FileOutputStream(file);
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlWriter = new XMLWriter(out,format);
            xmlWriter.write(document);
            out.close();

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    public static List<Element> getHeaders(Document document){
        Element root = document.getRootElement();
        List<Element> elements = root.elements();
        List<Element> result = new ArrayList<Element>();
        Iterator<Element> it = elements.iterator();
        while (it.hasNext()){
            forRead(it.next(),result);
        }
        return result;
    }

    public static void forRead(Element e,List<Element> result){
        String name = e.attributeValue("name");
        if(name!=null && name.equals("android.view.preference-headers")){
            result.add(e);
        }
        List<Element> list = e.elements();
        Iterator<Element> it = list.iterator();
        while (it.hasNext()){
            forRead(it.next(),result);
        }
    }

    public static void getXpath(Element e,List<String> list){
        String tar = e.attributeValue("targetInteractionFlowElement");
        if(tar!=null && !tar.isEmpty()){
            tar = tar.substring(1,tar.length()).replaceAll("@","").replaceAll("^\\.\\d+$","");
            String[] tars = tar.split("/");
            StringBuffer sb = new StringBuffer();
            for (int i=1;i<tars.length;i++){
                String t = tars[i];
                if(tars[i].contains(".")){
                    int num = Integer.parseInt(t.substring(t.indexOf(".")+1,t.length()));
                    num++;   //xpath的索引从1开始
                    t = t.substring(0,t.indexOf("."))+"["+num+"]";

                }
                sb.append("/"+t);
            }
            list.add("core:IFMLModel"+sb.toString());
        }
        List<Element> es = e.elements();
        Iterator<Element> it = es.iterator();
        while (it.hasNext()){
            getXpath(it.next(),list);
        }
    }

    public static List<Element> getTargetElement(Document document,List<String> xpath){
        List<Element> result = new ArrayList<Element>();
        Iterator<String> it = xpath.iterator();
        while (it.hasNext()){
            List<Element> list = document.selectNodes(it.next());
            if(list.size()>0)
                result.add(list.get(0));
        }
        return result;
    }
}
